import socket


def send_message(ip, port, message):
    try:
        # 创建一个socket对象
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            # 连接到指定的IP和端口
            s.connect((ip, port))
            # 发送消息
            s.sendall(message.encode('utf-8'))
            print(f"Message sent to {ip}:{port}")
    except Exception as e:
        print(f"An error occurred: {e}")


def send_message_continuous(ip, port):
    try:
        # 创建一个socket对象
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            # 连接到指定的IP和端口
            s.connect((ip, port))
            print(f"Connected to {ip}:{port}")

            while True:
                # 从用户输入读取消息
                message = input("Enter message to send (type 'exit' to quit): ")
                if message.lower() == 'exit':
                    print("Exiting...")
                    break

                # 发送消息
                s.sendall(message.encode('utf-8'))
                print(f"Message sent to {ip}:{port}")

    except Exception as e:
        print(f"An error occurred: {e}")



ip = "8.221.142.189"  # 替换为指定机器的IP地址
port = 12345  # 替换为监听的端口

# 单次发送消息
send_message(ip, port, "你好世界")

# 持续发送消息
# send_message_continuous(ip, port)